﻿using System;
using System.Threading.Tasks;

namespace Demo
{
    public interface IExceptionHandlerFeature
    {
        string Path { get; }
        Exception Error { get; }
    }

    public class ExceptionHandlerFeature : IExceptionHandlerFeature
    {
        public Exception Error { get; set; }

        public string Path { get; set; }
    }

    public class ExceptionHandlerMiddleware
    {
        private readonly RequestDelegate _next;
        public ExceptionHandlerMiddleware(RequestDelegate next)
        {
            if (next == null)
            {
                throw new ArgumentNullException(nameof(next));
            }

            _next = next;
        }

        public async Task Invoke(RequestContext context)
        {
            try
            {
                var exception = context.Features.Get<IExceptionHandlerFeature>();
                if (null != exception)
                {
                    await Console.Out.WriteLineAsync(exception.Path + ":" + exception.Error.Message);
                }
                else
                {
                    await _next(context);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("An unhandled exception has occurred: " + ex.Message);
                try
                {
                    var exceptionHandlerFeature = new ExceptionHandlerFeature()
                    {
                        Error = ex,
                        Path =context.Url,
                    };
                    context.Features.Set<IExceptionHandlerFeature>(exceptionHandlerFeature);
                    return;
                }
                catch (Exception ex2)
                {
                    Console.WriteLine("An exception was thrown attempting to execute the error handler.");
                }
                throw;
            }
        }
    }
}